package gee

import (
	"encoding/json"
	"fmt"
	"net/http"
)

type H map[string]interface{}

type Context struct {
	Response http.ResponseWriter
	Req      *http.Request
	Code     int
	Path     string
	Method   string
	Params   map[string]string
	// middleware
	handlers []HandlerFunc
	index    int
}

func (c *Context) Status(code int) {
	c.Code = code
	c.Response.WriteHeader(code)
}
func (c *Context) String(code int, format string, values ...interface{}) {
	c.SetHeader("Content-Type", "text/plain")
	c.Status(code)
	c.Response.Write([]byte(fmt.Sprintf(format, values...)))
}
func (c *Context) Query(key string) string {
	return c.Req.URL.Query().Get(key)
}
func (c *Context) Param(key string) string {
	value, _ := c.Params[key]
	return value
}
func (c Context) SetHeader(key string, value string) {
	c.Response.Header().Set(key, value)
}
func (c Context) SetStatues(code int) {
	c.Response.WriteHeader(code)
}
func (c Context) Json(code int, obj interface{}) {
	c.SetStatues(code)
	encoder := json.NewEncoder(c.Response)
	if err := encoder.Encode(obj); err != nil {
		http.Error(c.Response, err.Error(), 500)
	}
}
func newContext(w http.ResponseWriter, req *http.Request) *Context {
	return &Context{
		Response: w,
		Req:      req,
		Path:     req.URL.Path,
		Method:   req.Method,
		index:    -1,
	}
}
func (c *Context) Next() {
	c.index++
	s := len(c.handlers)
	for ; c.index < s; c.index++ {
		c.handlers[c.index](c)
	}
}
